
<template>
  <view class="uni-container">
    <uni-forms ref="form" v-model="formData" :rules="rules" validateTrigger="bind">
		<uni-forms-item name="college_name" label="名称">
			<uni-easyinput placeholder="学院名称" v-model="formData.college_name" />
		</uni-forms-item>
		<uni-forms-item name="college_id" label="ID">
			<uni-easyinput placeholder="学院ID" type="number" v-model="formData.college_id" />
		</uni-forms-item>
		<uni-forms-item name="description" label="描述">
			<textarea placeholder="请输入学院描述" class="uni-textarea-border" v-model="formData.description" ></textarea>
		</uni-forms-item>
		<uni-forms-item name="sort" label="排序">
			<uni-easyinput placeholder="学院显示顺序" type="number" v-model="formData.sort" />
		</uni-forms-item>

      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator url="/pages/system/college/list" style="margin-left: 15px;">
            <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import validator from '@/js_sdk/validator/college.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'hr-college';

  function getValidator(fields) {
    let reuslt = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        reuslt[key] = validator[key]
      }
    }
    return reuslt
  }

  export default {
    data() {
      return {
        formOptions: {},
        formData: {
			"college_name": "",
			"college_id": null,
			"description": "",
			"sort": null
		},
        rules: {
          ...getValidator(["college_name","college_id","description","sort"])
        }
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      /**
       * 触发表单提交
       */
      submit() {
        uni.showLoading({
			title: '提交中...',
			mask: true
        })
        this.$refs.form.submit().then((res) => {
          this.submitForm(res)
        }).catch((errors) => {
          uni.hideLoading()
        })
      },

      submitForm(value) {
        // 使用 uni-clientDB 提交数据
        db.collection(dbCollectionName).add(value).then((res) => {
          uni.showToast({
            title: '新增成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateTo({
						url: '/pages/system/college/list'
					}), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>

